<template>
  <page-layout :title="description">
    <a-card :bordered="false">

      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <a-button ghost type="danger" @click="showCancelWriteOffModal">取消核销</a-button>
        <a-button ghost type="primary" @click="showInvoiceNumberModal">录入发票号</a-button>
        <!--      <a-button ghost type="danger" @click="showUpdateInvoiceNumberModal" style="color: #FF9933;border-color: #FF9933">-->
        <!--        修改/作废发票-->
        <!--      </a-button>-->
        <a-button type="primary" icon="download" @click="handleExportXls('账单信息')">导出</a-button>
        <j-super-query :fieldList="fieldList" ref="superQueryModal"
                       @handleSuperQuery="handleSuperQuery"></j-super-query>
        <!--      <a-dropdown v-if="selectedRowKeys.length > 0">-->
        <!--        <a-menu slot="overlay">-->
        <!--          <a-menu-item key="1" @click="batchDel">-->
        <!--            <a-icon type="delete" />-->
        <!--            删除-->
        <!--          </a-menu-item>-->
        <!--        </a-menu>-->
        <!--        <a-button style="margin-left: 8px"> 批量操作-->
        <!--          <a-icon type="down" />-->
        <!--        </a-button>-->
        <!--      </a-dropdown>-->
      </div>

      <a-table
        ref="table"
        size="small"
        bordered
        rowKey="id"
        class="j-table-force-nowrap"
        :scroll="{x:1500}"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">
        <span slot="action" slot-scope="text, record">
          <a @click="detail(record)"><a-icon type="copy"></a-icon>费用详情</a>
                <a-divider v-if="record.status!=4" type="vertical" />
          <a-dropdown v-if="record.status!=4">
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item v-if="record.status==2 || record.status==3">
                <a @click="showPartCancelModal(record)"><a-icon type="tag"></a-icon>费用核销</a>
              </a-menu-item>
              <a-menu-item v-if="record.status==2">
                <a @click="showUpdateInvoiceNumberModal(record)"> <a-icon type="highlight"></a-icon>修改/作废发票</a>
              </a-menu-item>
              <a-menu-item v-if="record.status==1">
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a><a-icon type="delete"></a-icon>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>

        </span>
      </a-table>

      <j-modal
        :title="modalTitle"
        :visible="detailVisible"
        :maskClosable="false"
        switchFullscreen
        :width="1200"
        @ok="handleCancelModal"
        @cancel="handleCancelModal">
        <a-table
          :columns="detailColumns"
          :loading="detailModalLoading"
          size="small"
          :scroll="{x:800}"
          :pagination=false
          :data-source="detailData"
        />
      </j-modal>
      <!-- 部分核销 -->
      <j-modal
        :title="partCancelTitle"
        :visible="partCancelVisible"
        :maskClosable="false"
        @ok="handlePartCancelSave"
        @cancel="handlePartCancelModal">
        <BillCancelForm ref="bcForm" :data="cancelData" @cb="verificationCallBack"></BillCancelForm>
      </j-modal>
      <a-modal
        title="提示"
        :visible="cancelWriteOffModalVisible"
        :width="300"
        :confirm-loading="confirmLoading"
        @ok="cancelWriteOffModalHandleOk"
        @cancel="cancelWriteOffModalHandleCancel"
      >
        是否取消核销？
      </a-modal>
      <a-modal
        :title="invoiceModalTitle"
        :visible="invoiceModalVisible"
        :maskClosable="false"
        :confirm-loading="confirmLoading1"
        :okText="invoiceOkText"
        :cancelText="invoiceCancelText"
        :cancelButtonProps="cancelButtonProps"
        @ok="handleInputInvoiceNumberOk"
        @cancel="handleInputInvoiceNumberCancel"
      >
        <!--{ props: {ghost: true,type: 'danger'} }-->
        <a-row style="line-height: 35px">
          <a-col span="6">
            开票时间:
          </a-col>
          <a-col span="12">
            <j-date placeholder="请选择开票时间" v-model="billingTime"
                    :trigger-change="true"
                    style="width: 100%" date-format="YYYY-MM-DD HH:mm:ss" :show-time=true />
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px;line-height: 35px">
          <a-col span="6">
            发票号码:
          </a-col>
          <a-col span="12">
            <a-select mode="tags" style="width: 100%" placeholder="多个用回车分开" @change="invoiceNumberHandleChange"
                      v-model="invoiceNumber">
            </a-select>
          </a-col>
        </a-row>
      </a-modal>
    </a-card>
  </page-layout>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
import '@/assets/less/TableExpand.less'
import JSuperQuery from '@/components/jeecg/JSuperQuery.vue'
import Vue from 'vue'
import { getAction, httpAction } from '@api/manage'
import { fmoney } from '@api/api'
import BillCancelForm from '@views/bill/modules/BillCancelForm'
import JDate from '@/components/jeecg/JDate'

import PageLayout from '@/components/page/PageLayout'

const superQueryFieldList = [
  {
    type: 'select',
    text: '账单属性',
    value: 'billAttr',
    options: [
      { label: '应收', value: 1 },
      { label: '预收', value: 2 },
      { label: '应付', value: 3 },
      { label: '预付', value: 4 }
    ]
  },
  {
    type: 'string',
    text: '账单号',
    value: 'billNumber'
  },
  {
    type: 'string',
    text: '发票号',
    value: 'invoiceNumber'
  },
  {
    type: 'date',
    text: '开票时间',
    value: 'billingTime'
  },
  {
    type: 'date',
    text: '创建时间',
    value: 'createTime'
  },
  {
    type: 'date',
    text: '核销时间',
    value: 'verificationTime'
  },
  {
    type: 'string',
    text: '创建人',
    value: 'createUser'
  },
  {
    type: 'select',
    text: '状态',
    value: 'status',
    options: [
      { label: '未核销', value: 1 },
      { label: '未开票', value: 2 },
      { label: '部分核销', value: 3 },
      { label: '已完成', value: 4 }
    ]
  },
  {
    type: 'string',
    text: '发票抬头',
    value: 'invoiceTitle'
  },
  {
    type: 'select',
    text: '币种',
    value: 'currency',
    dictCode: 'currency'

  },

  {
    type: 'string',
    text: '对账金额',
    value: 'amount'
  }]
export default {
  name: 'BillInfoList',
  mixins: [JeecgListMixin],
  components: {
    BillCancelForm,
    JDictSelectTag,
    JSuperQuery,
    JDate,
    PageLayout
  },
  data() {
    return {
      actionRowId: '',
      invoiceAction: 1,
      invoiceModalTitle: '录入发票',
      invoiceOkText: '确定',
      cancelButtonProps: {},
      invoiceCancelText: '取消',
      billingTime: '',
      invoiceNumber: [],
      invoiceModalVisible: false,
      cancelWriteOffModalVisible: false,
      cancelData: {},
      partCancelTitle: '',
      partCancelVisible: false,
      detailModalLoading: false,
      modalTitle: '',
      detailVisible: false,
      fieldList: superQueryFieldList,
      manyModalVisible: false,
      confirmLoading: false,
      confirmLoading1: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      form: this.$form.createForm(this),
      description: '账单管理',
      // 表头
      columns: [
        // {
        //   title: '#',
        //   dataIndex: '',
        //   key: 'rowIndex',
        //   width: 60,
        //   align: 'center',
        //   customRender: function(t, r, index) {
        //     return parseInt(index) + 1
        //   }
        // },
        {
          title: '账单属性',
          align: 'center',
          width: 100,
          dataIndex: 'billAttr',
          customRender: function(text) {
            if (text == '1') {
              return <a-tag color="#99CC66">
                应收
              </a-tag>
            } else if (text == '2') {
              return <a-tag color="#66CCCC">
                预收
              </a-tag>
            } else if (text == '3') {
              return <a-tag color="#FF6600">
                应付
              </a-tag>
            } else if (text == '4') {
              return <a-tag color="#FF0033">
                预付
              </a-tag>
            }
          }
        },
        {
          title: '状态',
          align: 'center',
          width: 100,
          dataIndex: 'status',
          customRender: function(text) {
            if (text == '1') {
              return '未开票'
            } else if (text == '2') {
              return '未核销'
            } else if (text == '3') {
              return '部分核销'
            } else if (text == '4') {
              return '已完成'
            }
          }
        },
        {
          title: '账单号',
          align: 'center',
          width: 180,
          dataIndex: 'billNumber'
        },
        {
          title: '发票号',
          align: 'center',
          width: 200,
          dataIndex: 'invoiceNumber',
          ellipsis: true
        },
        {
          title: '开票时间',
          align: 'center',
          width: 200,
          dataIndex: 'billingTime'
        },
        {
          title: '创建时间',
          align: 'center',
          width: 200,
          dataIndex: 'createTime'
        },
        {
          title: '核销(取消)时间',
          align: 'center',
          width: 200,
          dataIndex: 'verificationTime'
        },
        {
          title: '核销币种',
          align: 'center',
          width: 100,
          dataIndex: 'verificationCurrency'
        },
        {
          title: '已核销金额',
          align: 'center',
          width: 150,
          dataIndex: 'writeOffAmount'
        },
        {
          title: '创建人',
          align: 'center',
          width: 150,
          dataIndex: 'createUser'
        },
        {
          title: '发票抬头',
          align: 'left',
          width: 200,
          dataIndex: 'invoiceTitle',
          ellipsis: true
        },
        {
          title: '币种',
          align: 'center',
          width: 100,
          dataIndex: 'currency'
        },
        {
          title: '结算单位',
          align: 'left',
          width: 200,
          dataIndex: 'settlementCompany_dictText',
          ellipsis: true
        },
        {
          title: '对账金额',
          align: 'right',
          width: 150,
          dataIndex: 'amount',
          customRender: function(text) {
            return fmoney(text, 3)
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/box.bill/list',
        delete: '/box.bill/delete'
      },
      pagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '100', '200']
      },
      superQueryFlag: false,
      superQueryParams: '',
      detailData: [],
      detailColumns: [
        {
          title: '费用状态',
          dataIndex: 'status',
          width: '300px'
        },
        {
          title: '费用名称',
          dataIndex: 'costName_dictText',
          width: '200px'
        },
        {
          title: '币种',
          dataIndex: 'currency',
          width: '100px'
        },
        {
          title: '结算单位',
          dataIndex: 'settlementCompany_dictText',
          width: '300px'
        },
        {
          title: '计费单位',
          dataIndex: 'chargingUnit_dictText',
          width: '200px'
        },
        {
          title: '数量',
          dataIndex: 'num',
          width: '150px'
        },
        {
          title: '单价',
          dataIndex: 'price',
          width: '150px',
          customRender: function(text) {
            return fmoney(text, 2)
          }
        },
        {
          title: '总价',
          dataIndex: 'totalPrice',
          width: '100px',
          customRender: function(text) {
            return fmoney(text, 2)
          }
        },
        {
          title: '汇率',
          dataIndex: 'rate',
          width: '100px'
        },
        {
          title: '开票汇率',
          dataIndex: 'invoiceRate',
          width: '150px'
        },
        {
          title: '账单类型',
          dataIndex: 'billType',
          width: '150px'
        },
        {
          title: '账单号',
          dataIndex: 'billNumber',
          width: '300px'
        },
        {
          title: '发票号',
          dataIndex: 'invoiceNumber',
          width: '300px'
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: '300px'
        }
      ]
    }
  },
  created() {
  },
  computed: {},
  methods: {
    initDictConfig() {
    },
    handleCancel(e) {
      this.manyModalVisible = false
    },
    handleCancelModal() {
      this.detailVisible = false
      this.detailData = []
    },
    handlePartCancelModal() {
      this.partCancelVisible = false
    },
    handlePartCancelSave() {
      this.$refs.bcForm.handleOk()
    },
    showPartCancelModal(row) {
      this.cancelData = row
      setTimeout(() => {
        this.$refs.bcForm.setValue()
      }, 10)
      this.partCancelVisible = true
      this.partCancelTitle = '账单核销-' + row.billNumber
    },
    detail(row) {
      if (row.billAttr == '1') {
        this.modalTitle = '应收明细'
      } else if (row.billAttr == '2') {
        this.modalTitle = '预收明细'
      } else if (row.billAttr == '3') {
        this.modalTitle = '应付明细'
      } else if (row.billAttr == '4') {
        this.modalTitle = '预付明细'
      }
      this.detailModalLoading = true
      this.detailVisible = true
      let url = '/box.trade/jzxTrade/queryCostInfoByBillNumber', params = { billNumber: row.billNumber }
      console.log(params)
      getAction(url, params).then(res => {
        let { result } = res
        if (result) {
          if (Array.isArray(result)) {
            this.detailData = result
          } else if (Array.isArray(result.records)) {
            this.detailData = result.records
          }
          this.detailModalLoading = false
        }
      }).finally(() => {
      })
    },
    verificationCallBack(e) {
      if (e) {
        this.loadData()
        this.partCancelVisible = false
      }
    },
    showCancelWriteOffModal() {
      let srs = this.selectionRows
      if (srs.length == 0) {
        this.$message.warning('请选择一条或多条账单')
      } else {
        let flag = true
        for (let i = 0; i < srs.length; i++) {
          if (srs[i].status != '4' && srs[i].status != '3') {
            this.$message.warning('请选择已完成或已核销的账单进行操作')
            flag = false
            break
          }
        }
        if (flag) {
          this.cancelWriteOffModalVisible = true
        }
      }
    },
    cancelWriteOffModalHandleOk() {
      if (this.invoiceAction == 1) {
        let srs = this.selectionRows
        let flag = true
        this.confirmLoading = true
        let ids = ''
        for (let i = 0; i < srs.length; i++) {
          ids += srs[i].id + ','
        }
        if (flag) {
          let url = '/box.bill/cancel/verification', params = 'ids=' + ids.substring(0, ids.length - 1), method = 'post'
          httpAction(url, params, method).then(res => {
            if (res.success) {
              this.$message.success(res.message)
            } else {
              this.$message.warning(res.message)
            }
            this.loadData()
            this.confirmLoading = false
            this.cancelWriteOffModalVisible = false
          }).finally(() => {
          })
        }
      } else if (this.invoiceAction == 2) {

      }

    },

    cancelWriteOffModalHandleCancel() {
      this.cancelWriteOffModalVisible = false
    },
    getTime: function() {
      var _this = this
      let yy = new Date().getFullYear()
      let mm = new Date().getMonth() + 1
      let dd = new Date().getDate()
      let hh = new Date().getHours()
      let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
      let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
      return yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
    },
    showInvoiceNumberModal() {
      let srs = this.selectionRows
      if (srs.length == 0) {
        this.$message.warning('请选择一条或多条账单')
      } else {
        let flag = true
        for (let i = 0; i < srs.length; i++) {
          if (srs[i].status != '1') {
            this.$message.warning('请选择未开票的账单进行操作')
            flag = false
            break
          }
        }
        if (flag) {
          this.invoiceAction = 1
          this.invoiceNumber = []
          this.billingTime = this.getTime()
          this.invoiceModalTitle = '录入发票'
          this.invoiceCancelText = '取消'
          this.invoiceOkText = '确定'
          this.cancelButtonProps = {}
          this.invoiceModalVisible = true
        }
      }
    },
    handleInputInvoiceNumberOk() {
      if (this.invoiceAction == 1) {
        let srs = this.selectionRows
        let flag = true
        this.confirmLoading1 = true
        let ids = ''
        for (let i = 0; i < srs.length; i++) {
          ids += srs[i].id + ','
        }
        if (flag) {
          let invoiceNumber = this.invoiceNumber.toString().trim().replaceAll(' ', '')
          let billingTime = this.billingTime
          if (invoiceNumber == '' || billingTime == '') {
            this.$message.warning('请填写发票号和开票时间')
            this.confirmLoading1 = false
          } else {
            let url = '/box.bill/save/invoice',
              params = 'ids=' + ids.substring(0, ids.length - 1) + '&invoiceNumber=' + invoiceNumber + '&billingTime=' + billingTime,
              method = 'post'
            console.log(params)
            httpAction(url, params, method).then(res => {
              if (res.success) {
                this.$message.success(res.message)
              } else {
                this.$message.warning(res.message)
              }
              this.loadData()
              this.confirmLoading1 = false
              this.invoiceModalVisible = false
            }).finally(() => {
            })
          }
        }
      } else if (this.invoiceAction == 2) {
        let invoiceNumber = this.invoiceNumber.toString().trim().replaceAll(' ', '')
        let billingTime = this.billingTime
        if (invoiceNumber == '' || billingTime == '') {
          this.$message.warning('请填写发票号和开票时间')
          this.confirmLoading1 = false
        } else {
          let url = '/box.bill/update/invoice',
            params = 'id=' + this.actionRowId + '&invoiceNumber=' + invoiceNumber + '&billingTime=' + billingTime + '&flag=' + 1,
            method = 'post'
          console.log(params)
          httpAction(url, params, method).then(res => {
            if (res.success) {
              this.$message.success(res.message)
            } else {
              this.$message.warning(res.message)
            }
            this.loadData()
            this.confirmLoading1 = false
            this.invoiceModalVisible = false
          })
        }
      }

    },
    showUpdateInvoiceNumberModal(record) {
      this.actionRowId = record.id
      this.invoiceAction = 2
      this.invoiceModalTitle = '修改/作废发票'
      this.invoiceCancelText = '作废发票'
      this.invoiceOkText = '修改发票'
      this.cancelButtonProps = { props: { ghost: true, type: 'danger' } }
      this.invoiceNumber = record.invoiceNumber.split(',')
      this.billingTime = record.billingTime
      this.invoiceModalVisible = true
    },
    handleInputInvoiceNumberCancel() {
      if (this.invoiceAction == 1) {
        this.invoiceModalVisible = false
      } else if (this.invoiceAction == 2) {
        let url = '/box.bill/update/invoice',
          params = 'id=' + this.actionRowId + '&invoiceNumber=n&billingTime=n&flag=' + 2,
          method = 'post'
        console.log(params)
        httpAction(url, params, method).then(res => {
          if (res.success) {
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message)
          }
          this.loadData()
          this.confirmLoading1 = false
          this.invoiceModalVisible = false
        })
      }
    },
    invoiceNumberHandleChange(value) {
      console.log(value.toString())
    },
    // handleClickRow(record, index) {
    //   return {
    //     on: {
    //       click: () => {
    //         console.log(record, index)
    //         console.log('点击行内容record' + record)
    //         console.log('序号索引index' + index)
    //       }
    //     }
    //   }
    // },
    //高级查询方法
    handleSuperQuery(arg) {
      if (!arg) {
        this.superQueryParams = ''
        this.superQueryFlag = false
      } else {
        this.superQueryFlag = true
        this.superQueryParams = JSON.stringify(arg)
      }
      this.loadData()
    },
    // 获取查询条件
    getQueryParams() {
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return this.filterObj(param)
    },
    filterObj(obj) {
      if (!(typeof obj == 'object')) {
        return
      }

      for (let key in obj) {
        if (obj.hasOwnProperty(key)
          && (obj[key] == null || obj[key] == undefined || obj[key] === '')) {
          delete obj[key]
        }
      }
      return obj
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
<style>
.ant-table {
  min-height: 460px !important;
}

.ant-empty-normal {
  margin: 140px 0 !important;
}
</style>